/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7

import SMSHelper 1.0

Rectangle {
    id: invitationsendingdlg
    width: 300
    height: 230
    gradient: Gradient {
        GradientStop {
            position: 0.44
            color: "#abd1ee"
        }

        GradientStop {
            position: 1
            color: "#000000"
        }
    }
    z: 50

    signal invitedMembers(variant memberlist)

    property string datacloudurl: ""
    property string username: ""
    property string password: ""
    property string karpoid: ""

    property string carpoolkarpoid: ""

    property string invitationstring: "Hi! Want to join my carpool? More information from the attached link. "

    function setMembersToInvite(membersstr)
    {
        invitationlist.clear()

        var members = JSON.parse(membersstr)
        for (var m=0;m<members.length;m++)
        {

            if (members[m].status == "uninvited")
            {
                invitationlist.append({"phone":members[m].phone,"karpoid":members[m].carpoolmemberkarpoid})
                console.log("INVITE: phone: " + members[m].phone)
            }

        }

        if (invitationlist.count < 1)
        {
            messagebox.text = "There is no uninvited members."
            messagebox.show("")
        }

        invitationtextinput.text = invitationstring

    }

    SMSHelper
    {
        id: smshelper
        property string state: "InactiveState" //     enum State { InactiveState = 0, ActiveState,  CanceledState,  FinishedState };

        onStateMsg:
        {
            console.log("SMSHELPER: state " + statemsg)

            state = statemsg
            if (sendinginvitations)
            {
                sendNextInvitation()
            }

        }

        onDebugMsg:
        {
            console.log("SMSHELPER: debug " + dbgmsg)
        }

        onErrorMsg:
        {
            console.log("SMSHELPER: error " + errormsg)
        }


        property bool sendinginvitations: false
        property int currentinvitationindex: -1
        property variant invitedarray: []

        function sendNextInvitation()
        {
            if (state == "InactiveState" || state == "FinishedState")
            {
                var array = []
                for (var i=0; i<invitedarray.length;i++)
                {
                    array[i] = invitedarray[i]
                }
                currentinvitationindex++
                if (currentinvitationindex < invitationlist.count)
                {
                    messagebox.text = "Sending invitations ... " + (currentinvitationindex+1) + "/" + invitationlist.count

                    var message = invitationtextinput.text + datacloudurl + "/Membership?id=" + invitationlist.get(currentinvitationindex).karpoid


                    console.log("InvitationSending::sendNextInvitation MESSAGE: \r\n\r\n" + message + "\r\n\r\n")

                    var phone = invitationlist.get(currentinvitationindex).phone
                    if (!sendsms(phone, message))
                    {
                        messagebox.text = "Failed to send sms to " + phone + "<br>Stopped sending invitations."
                        messagebox.show("")
                        sendinginvitations = false
                    }
                    else
                    {
                        array[currentinvitationindex] = invitationlist.get(currentinvitationindex).karpoid
                        invitedarray = array
                    }
                }
                else
                {
                    // all sent
                    messagebox.visible = false
                    invitationsendingdlg.invitedMembers(array)
                    invitationsendingdlg.visible = false
                    sendinginvitations = false
                }

            }
        }

        function sendinvitations()
        {
            sendinginvitations = true
            currentinvitationindex = -1
            var array = []
            invitedarray = array
            sendNextInvitation()

            messagebox.text = "Sending invitations ... "
            messagebox.show("")

        }


    }

    MessageBox
    {
        id: messagebox
    }

    ListModel
    {
        id: invitationlist
        // phone
        // karpoid <= this is the id in the carpoolmembesindex
    }


    Rectangle
    {
        id: titlerect
        width: 110
        height: 29
        color: "#5d8eac"
        anchors.right: parent.right
        anchors.rightMargin: 0
        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.top: parent.top
        anchors.topMargin: 0

        Text {
            id: titleid
            width: 110
            height: 29
            text: "Invitation sending"
            font.family: "Arial"
            anchors.leftMargin: 10
            anchors.fill: parent
            anchors.verticalCenter: titlerect.verticalCenter
            font.pixelSize: 16
        }

        MouseArea {
            id: titlerectmousearea
            anchors.fill: parent

            drag.target: invitationsendingdlg
            drag.axis: Drag.XandYAxis
            drag.minimumX: 0
            drag.maximumX: 1000
            drag.minimumY: 0
            drag.maximumY: 1000
        }
    }



    Text {
        id: invitationtextid
        width: 150
        text: "Invitation text"
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.right: parent.right
        anchors.top: titlerect.bottom
        anchors.topMargin: 5
        font.pixelSize: 14
    }

    Rectangle {
        id: invitationtextinputrectangle
        height: 14*10
        color: "#ffffff"
        anchors.right: parent.right
        anchors.rightMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.top: invitationtextid.bottom
        anchors.topMargin: 5


        border.color: "#000901"

        TextEdit  {
            id: invitationtextinput
            text: ""
            anchors.leftMargin: 3
            anchors.topMargin: 3
            anchors.fill: parent
            selectionColor: "#316ac5"
            wrapMode: TextEdit.Wrap
            font.pixelSize: 14
        }
    }

    PushButton
    {
        id: sendid
        label: "Send"
        width: 80
        anchors.right: parent.right
        anchors.rightMargin: 10
        anchors.top: invitationtextinputrectangle.bottom
        anchors.topMargin: 5

        onButtonpressed:
        {
            console.log("COUNT: "+  invitationlist.count)
            smshelper.sendinvitations()
        }

    }

    PushButton
    {
        id: cancelid
        label: "Cancel"
        width: 80
        anchors.right: sendid.left
        anchors.rightMargin: 20
        anchors.top: invitationtextinputrectangle.bottom
        anchors.topMargin: 5

        onButtonpressed:
        {
            invitationsendingdlg.visible = false
        }

    }
}
